<?php

namespace Hengha\Util;

class Helper
{
    public static function normalizeNewLine($str)
    {
        $a = trim(strip_tags($str), '<br><br />');
        $a = trim(str_ireplace(array('<br>', '<br />', '<br/>', '<br >', '　'), '#', $a));
        return preg_replace('/[#\s]+/', '<br />', $a);
    }

    public static function urlGet($url, $sourceEncoding = 'gbk', $retries = 3)
    {
        $context = stream_context_create(array(
            'http' => array(
                'method' => "GET",
                'timeout' => 60
            )
        ));

        $content = file_get_contents($url, false, $context);

        $i = 0;
        while ($i < $retries &&
            ($content === false ||
                ($http_response_header &&
                    stripos($http_response_header[0], '200 OK') === false))) {
            $content = file_get_contents($url, false, $context);
            $i = $i + 1;
        }
        preg_match('/[1-5]\d{2}/', $http_response_header[0], $matches);
        $statusCode = $matches[0];
        if ($content === false) {
            return array($statusCode, false);
        }
        if ($sourceEncoding && $sourceEncoding != 'utf-8') {
            return array($statusCode, mb_convert_encoding($content, 'utf-8', $sourceEncoding));
        }
        return array($statusCode, $content);
    }
}